﻿using UnityEngine;
using System;
using System.Collections;
using KBEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using DG.Tweening;
using UnityEngine.Assertions;

public class PlayerBaseInfo : MonoBehaviour
{

	// Use this for initialization
	void Start()
	{
		KBEngine.Event.registerOut("onCell2ClientMsg", this, "OnNameNetMsg");
		KBEngine.Event.registerOut("onCell2ClientMsg", this, "OnMailNetMsg");

		KBEngine.Event.registerOut("onNameChanged", this, "onNameChanged");
		KBEngine.Event.registerOut("onDisconnected", this, "onDisconnected");

		KBEngine.Event.registerOut("onHeadIconIDChanged", this, "onHeadIconIDChanged");
		KBEngine.Event.registerOut("onIsReceiveNewMailChanged", this, "onIsReceiveNewMailChanged");

		KBEngine.Event.registerOut("onContainerPropChanged", this, "onContainerPropChanged");

		transform.Find("btn_name").GetComponent<Button>().onClick.AddListener(OnNameBtnClick);
		transform.Find("pl_give_name/btn_confirm_name").GetComponent<Button>().onClick.AddListener(OnConfirmNameBtnClick);

		// 头像点击事件
		EventTrigger.Entry headIconClickup = new EventTrigger.Entry();
		headIconClickup.eventID = EventTriggerType.PointerUp;
		headIconClickup.callback.AddListener(new UnityAction<BaseEventData>(onHeadIconClickup));
		EventTrigger trigger = transform.Find("img_head").gameObject.AddComponent<EventTrigger>();
		trigger.triggers.Add(headIconClickup);

		// 邮件点击事件
		EventTrigger.Entry mailconClickup = new EventTrigger.Entry();
		mailconClickup.eventID = EventTriggerType.PointerUp;
		mailconClickup.callback.AddListener(new UnityAction<BaseEventData>(onMailIconClickup));
		transform.Find("pl_mail/img_mail").gameObject.AddComponent<EventTrigger>().triggers.Add(mailconClickup);

		onContainerPropChanged(KBEngineApp.app.player().id, "capitals", null, 0);
		onHeadIconIDChanged(0);
		onNameChanged("");
	}

	void OnDestroy()
	{
		KBEngine.Event.deregisterOut(this);
	}

	public void onMailIconClickup(BaseEventData data)
	{
		Transform trfPointer = transform.Find("pl_mail/img_mail/img_mail_pointer");
		//执行该方法，变化立即结束，且完成移动
		Tween tween = trfPointer.gameObject.GetComponent<CustomData>().objData as Tween;
		trfPointer.gameObject.GetComponent<CustomData>().objData = null;
		tween.Kill(true);

		List<object> msg = new List<object>();
		msg.Add(MsgDef.CLIENT2CELL_MAIL_MSG);
		msg.Add(MailDef.SUB_MSG_GET_MAIL_DATA);
		KBEngine.Event.fireIn("sendCellMsg", msg);

		//IKernel.Instance().sendCellMsg(msg);
	}

	public void onMailCloseBtnClick()
	{
		Transform trfMailDetailedInfo = transform.Find("pl_mail/pl_mail_detailed_info");
		trfMailDetailedInfo.gameObject.SetActive(false);

		Dictionary<UInt64, Image> mailDetailedInfoCtmData = trfMailDetailedInfo.GetComponent<CustomData>().objData as Dictionary<UInt64, Image>;
		foreach(var pairImg in mailDetailedInfoCtmData)
		{
			Destroy(pairImg.Value.gameObject);
		}
		trfMailDetailedInfo.GetComponent<CustomData>().objData = null;

		Image imgMailAttachment = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_txt/img_mail_attachment").GetComponent<Image>();
		Dictionary<Int32, Image> dictItemNum = imgMailAttachment.transform.GetComponent<CustomData>().objData as Dictionary<Int32, Image>;
		foreach (var pairItemNum in dictItemNum)
		{
			Destroy(pairItemNum.Value.gameObject);
		}
		imgMailAttachment.transform.GetComponent<CustomData>().objData = null;
	}

	public void onGetAttachmentBtnClick()
	{
		Image imgMailAttachment = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_txt/img_mail_attachment").GetComponent<Image>();
		Button btnGetAttachment = imgMailAttachment.transform.Find("btn_get_attachment").GetComponent<Button>();
		UInt64 selectMailID = btnGetAttachment.transform.GetComponent<CustomData>().uint64Data;

		Transform trfMailDetailedInfo = transform.Find("pl_mail/pl_mail_detailed_info");
		Dictionary<UInt64, Image> mailDetailedInfoCtmData = trfMailDetailedInfo.GetComponent<CustomData>().objData as Dictionary<UInt64, Image>;
		Image imgMailElem = null;
		if(!mailDetailedInfoCtmData.TryGetValue(selectMailID, out imgMailElem))
		{
			return;
		}

		if(imgMailElem.transform.GetComponent<CustomData>().int64Data == MailDef.State.GetAttachment)
		{
			return;
		}

		imgMailElem.transform.GetComponent<CustomData>().int64Data = MailDef.State.GetAttachment;
		List<object> msg = new List<object>();
		msg.Add(MsgDef.CLIENT2CELL_MAIL_MSG);
		msg.Add(MailDef.SUB_MSG_OP_MAIL);
		msg.Add(MailDef.State.GetAttachment);
		msg.Add(1);
		msg.Add(selectMailID);
		KBEngine.Event.fireIn("sendCellMsg", msg);

		//IKernel.Instance().sendCellMsg(msg);

		onMailElemClick(selectMailID);
	}

	public void onMailElemClick(UInt64 selectMailID)
	{
		Transform trfMailDetailedInfo = transform.Find("pl_mail/pl_mail_detailed_info");
		Dictionary<UInt64, Image> mailDetailedInfoCtmData = trfMailDetailedInfo.GetComponent<CustomData>().objData as Dictionary<UInt64, Image>;

		Image imgMailElem = null;
		foreach (var pairImg in mailDetailedInfoCtmData)
		{
			Color color = Color.white;
			if(pairImg.Key == selectMailID)
			{
				color = Color.grey;
				imgMailElem = pairImg.Value;
			}
			pairImg.Value.color = color;
		}

		if(imgMailElem == null)
		{
			return;
		}

		if(imgMailElem.transform.GetComponent<CustomData>().int64Data == MailDef.State.Unread)
		{
			imgMailElem.transform.GetComponent<CustomData>().int64Data = MailDef.State.Read;
			List<object> msg = new List<object>();
			msg.Add(MsgDef.CLIENT2CELL_MAIL_MSG);
			msg.Add(MailDef.SUB_MSG_OP_MAIL);
			msg.Add(MailDef.State.Read);
			msg.Add(1);
			msg.Add(selectMailID);
			KBEngine.Event.fireIn("sendCellMsg", msg);

			//IKernel.Instance().sendCellMsg(msg);
		}

		imgMailElem.transform.Find("img_state").GetComponent<Image>().sprite = Resources.Load("mail/mail_open", typeof(Sprite)) as Sprite;

		List<string> mailTxtInfo = imgMailElem.transform.GetComponent<CustomData>().objData as List<string>;
		string title = mailTxtInfo[0];
		string content = mailTxtInfo[1];
		string attachment = mailTxtInfo[2];
		Text txtMailRightTitle = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_txt/txt_mail_title").GetComponent<Text>();
		txtMailRightTitle.text = title;

		Text txtMailRightContent = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_txt/txt_mail_content").GetComponent<Text>();
		txtMailRightContent.text = content;

		Image imgMailAttachment = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_txt/img_mail_attachment").GetComponent<Image>();
		Button btnGetAttachment = imgMailAttachment.transform.Find("btn_get_attachment").GetComponent<Button>();
		btnGetAttachment.onClick.AddListener(onGetAttachmentBtnClick);
		btnGetAttachment.transform.GetComponent<CustomData>().uint64Data = selectMailID;

		Dictionary<Int32, Image> dictItemNum = imgMailAttachment.transform.GetComponent<CustomData>().objData as Dictionary<Int32, Image>;
		if (dictItemNum != null)
		{
			foreach (var pairItemNum in dictItemNum)
			{
				Destroy(pairItemNum.Value.gameObject);
			}
			imgMailAttachment.transform.GetComponent<CustomData>().objData = null;
		}

		if (attachment.Length == 0)
		{
			return;
		}

		Image imgIsGetAttachment = imgMailAttachment.transform.Find("img_is_get_attachment").GetComponent<Image>();
		imgIsGetAttachment.gameObject.SetActive(imgMailElem.transform.GetComponent<CustomData>().int64Data == MailDef.State.GetAttachment);
		btnGetAttachment.enabled = imgMailElem.transform.GetComponent<CustomData>().int64Data != MailDef.State.GetAttachment;

		imgMailAttachment.transform.gameObject.SetActive(true);
		imgMailAttachment.transform.GetComponent<CustomData>().objData = new Dictionary<Int32, Image>();

		Image imgItemNum = imgMailAttachment.transform.Find("img_item_num").GetComponent<Image>();

		string[] itemsNum = attachment.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
		for(int i = 0; i < itemsNum.Length; ++i)
		{
			string[] itemNum = itemsNum[i].Split(new char[1] { ':' }, StringSplitOptions.RemoveEmptyEntries);
			if(itemNum.Length != 2)
			{
				continue;
			}

			int itemID = Convert.ToInt32(itemNum[0]);
			int num =  Convert.ToInt32(itemNum[1]);
			Vector2 pos = new Vector2(imgItemNum.rectTransform.position.x + (imgItemNum.rectTransform.rect.width +10) * (i + 1), imgItemNum.rectTransform.position.y);
			Image imgItemNumClone = Instantiate(imgItemNum, pos, new Quaternion(0, 0, 0, 0), imgMailAttachment.transform);
			imgItemNumClone.gameObject.SetActive(true);
			string spriteName = String.Format("items/{0:D0}", itemID);
			imgItemNumClone.sprite = Resources.Load(spriteName, typeof(Sprite)) as Sprite;
			imgItemNumClone.transform.Find("txt_item_num").GetComponent<Text>().text = Convert.ToString(num);

			Dictionary<Int32, Image> dictItemsNum = imgMailAttachment.transform.GetComponent<CustomData>().objData as Dictionary<Int32, Image>;
			dictItemsNum[itemID] = imgItemNumClone;
		}
	}

	public void onNetMailMsg(List<object> listMsg)
	{
		Transform trfMailDetailedInfo = transform.Find("pl_mail/pl_mail_detailed_info");
		trfMailDetailedInfo.gameObject.SetActive(true);
		trfMailDetailedInfo.GetComponent<CustomData>().objData = new Dictionary<UInt64, Image>();
		Dictionary<UInt64, Image> mailDetailedInfoCtmData = trfMailDetailedInfo.GetComponent<CustomData>().objData as Dictionary<UInt64, Image>;
		trfMailDetailedInfo.Find("btn_close").GetComponent<Button>().onClick.AddListener(onMailCloseBtnClick);
		// 邮件简要元素
		Image imgMailElem = transform.Find("pl_mail/pl_mail_detailed_info/img_mail_elem").GetComponent<Image>();
		// 邮件滚动视图
		Transform trfMailScrollViewContent= transform.Find("pl_mail/pl_mail_detailed_info/sv_mail/Viewport/Content");

		int mailNum = Convert.ToInt32(listMsg[2]);
		int idx = 3;
		UInt64 firstMailID = 0;
		for(int i = 0; i < mailNum; ++i)
		{
			UInt64 mailID = Convert.ToUInt64(listMsg[idx++]);
			int state = Convert.ToInt32(listMsg[idx++]);
			int senderUid = Convert.ToInt32(listMsg[idx++]);
			string senderName = Convert.ToString(listMsg[idx++]);
			UInt64 receiverUid = Convert.ToUInt64(listMsg[idx++]);
			string title = Convert.ToString(listMsg[idx++]);
			string content = Convert.ToString(listMsg[idx++]);
			string attachment = Convert.ToString(listMsg[idx++]);
			Int64 sendTime = Convert.ToInt64(listMsg[idx++]);

			if(i == 0)
			{
				firstMailID = mailID;
			}

			Vector3 pos = new Vector3(imgMailElem.transform.position.x, imgMailElem.transform.position.y - i * (imgMailElem.rectTransform.rect.height + 5));
			Image imgMailElemClone = Instantiate(imgMailElem, pos, new Quaternion(0, 0, 0, 0), trfMailScrollViewContent);

			mailDetailedInfoCtmData = trfMailDetailedInfo.GetComponent<CustomData>().objData as Dictionary<UInt64, Image>;
			mailDetailedInfoCtmData[mailID] = imgMailElemClone;

			imgMailElemClone.transform.gameObject.SetActive(true);
			imgMailElemClone.transform.GetComponent<CustomData>().int64Data = state;
			imgMailElemClone.transform.GetComponent<CustomData>().objData = new List<string>();
			(imgMailElemClone.transform.GetComponent<CustomData>().objData as List<string>).Add(title);
			(imgMailElemClone.transform.GetComponent<CustomData>().objData as List<string>).Add(content);
			(imgMailElemClone.transform.GetComponent<CustomData>().objData as List<string>).Add(attachment);
			(imgMailElemClone.transform.GetComponent<CustomData>().objData as List<string>).Add(senderName);

			Image imgMailState = imgMailElemClone.transform.Find("img_state").GetComponent<Image>();
			string spriteName = state == 1 ? "mail/mail_close" : "mail/mail_open";
			Sprite spMailState = Resources.Load(spriteName, typeof(Sprite)) as Sprite;
			imgMailState.sprite = spMailState;

			Text txtMailTitle = imgMailElemClone.transform.Find("txt_mail_title").GetComponent<Text>();
			txtMailTitle.text = title;

			imgMailElemClone.transform.Find("txt_mail_sender_name").GetComponent<Text>().text = senderName;

			// 邮件点击事件
			EventTrigger.Entry mailconClickup = new EventTrigger.Entry();
			mailconClickup.eventID = EventTriggerType.PointerUp;
			mailconClickup.callback.AddListener(new UnityAction<BaseEventData>(
				(BaseEventData data) =>
				{
					onMailElemClick(mailID);
				}
			));
			imgMailElemClone.transform.gameObject.AddComponent<EventTrigger>().triggers.Add(mailconClickup);
		}
		Assert.IsTrue(idx == listMsg.Count);
		onMailElemClick(firstMailID);
	}

	public void onIsReceiveNewMailChanged(UInt16 oldHeadID)
	{
		Account acc = KBEngineApp.app.player() as Account;
		if (acc.isReceiveNewMail != 1)
		{
			return;
		}

		Transform trfPointer = transform.Find("pl_mail/img_mail/img_mail_pointer");
		Vector3 orgPos = trfPointer.position;
		Transform trfMail = transform.Find("pl_mail/img_mail");
		float moveHeight = trfMail.gameObject.GetComponent<RectTransform>().rect.height + trfPointer.gameObject.GetComponent<RectTransform>().rect.height;
		Tween tween = trfPointer.gameObject.GetComponent<CustomData>().objData as Tween;
		if (tween == null)
		{
			tween = DOTween.To(() => trfPointer.position, r => trfPointer.position = r, new Vector3(orgPos.x, orgPos.y - moveHeight), 1);
			trfPointer.gameObject.GetComponent<CustomData>().objData = tween;
			tween.OnComplete(() =>
				{
					trfPointer.position = orgPos;
					if (trfPointer.gameObject.GetComponent<CustomData>().objData as Tween != null)
					{
						onIsReceiveNewMailChanged(0);
					}
				}
			);
		}
		else
		{
			tween.Restart();
		}
	}

	public void onHeadIconClickup(BaseEventData data)
	{
		Image imgHeadIcons = transform.Find("pl_head_icons").GetComponent<Image>();
		imgHeadIcons.gameObject.SetActive(true);

		imgHeadIcons.transform.Find("btn_confirm_head_icon").GetComponent<Button>().onClick.AddListener(OnConfirmHeadIconBtnClick);

		CustomData headIconsCustomdata = transform.Find("pl_head_icons").GetComponent<CustomData>();
		headIconsCustomdata.objData = new Dictionary<Int32, Image>();

		Image imgRawHead = transform.Find("pl_head_icons/img_raw_head").GetComponent<Image>();

		int headIconNum = 10;
		for (int i = 1; i <= headIconNum; ++i)
		{
			Sprite spHeadIcon = Resources.Load(String.Format("head/head{0:D0}", i), typeof(Sprite)) as Sprite;
			if (spHeadIcon == null)
			{
				break;
			}

			Vector3 pos = new Vector3(imgRawHead.transform.position.x + (spHeadIcon.rect.width + 5) * (i - 1), imgRawHead.transform.position.y);
			Image imgClone = Instantiate<Image>(imgRawHead, pos, new Quaternion(0, 0, 0, 0), imgHeadIcons.transform);
			imgClone.gameObject.SetActive(true);
			imgClone.GetComponent<CustomData>().int64Data = i;
			imgClone.sprite = spHeadIcon;

			EventTrigger.Entry headIconClickup = new EventTrigger.Entry();
			headIconClickup.eventID = EventTriggerType.PointerUp;
			UnityAction<BaseEventData> evAct = new UnityAction<BaseEventData>(
				(BaseEventData evData) =>
				{
					onRawHeadIconClickup(evData, imgClone);
				}
			);
			headIconClickup.callback.AddListener(evAct);
			imgClone.gameObject.AddComponent<EventTrigger>().triggers.Add(headIconClickup);

			((Dictionary<Int32, Image>)headIconsCustomdata.objData)[i] = imgClone;
		}
	}

	public void onRawHeadIconClickup(BaseEventData evData, Image imgClone)
	{
		Int64 headIconID = imgClone.GetComponent<CustomData>().int64Data;
		CustomData headIconsCustomdata = transform.Find("pl_head_icons").GetComponent<CustomData>();
		headIconsCustomdata.int64Data = headIconID;
		Dictionary<Int32, Image> cloneImgs = headIconsCustomdata.objData as Dictionary<Int32, Image>;
		foreach (var pairImg in cloneImgs)
		{
			if (pairImg.Key == headIconID)
			{
				pairImg.Value.color = new Color32(217, 217, 243, 255);
			}
			else
			{
				pairImg.Value.color = new Color32(255, 255, 255, 255);
			}
		}
	}

	public void OnConfirmHeadIconBtnClick()
	{
		CustomData headIconsCustomdata = transform.Find("pl_head_icons").GetComponent<CustomData>();
		Int64 headIconID = headIconsCustomdata.int64Data;
		if (headIconID == 0)
		{
			return;
		}

		Dictionary<Int32, Image> cloneImgs = headIconsCustomdata.objData as Dictionary<Int32, Image>;
		foreach (var cloneImg in cloneImgs.Values)
		{
			Destroy(cloneImg.gameObject);
		}
		headIconsCustomdata.objData = null;

		transform.Find("pl_head_icons").GetComponent<Image>().gameObject.SetActive(false);

		List<object> msg = new List<object>();
		msg.Add(MsgDef.CLIENT2CELL_HALL_MSG);
		msg.Add(RoomDef.SUBMSG_SETUP_HEAD_ICON);
		msg.Add(headIconID);
		KBEngine.Event.fireIn("sendCellMsg", msg);

		//IKernel.Instance().sendCellMsg(msg);
	}

	public void OnConfirmNameBtnClick()
	{
		InputField ifGiveName = transform.Find("pl_give_name/if_give_name").GetComponent<InputField>();
		if (ifGiveName.text.Length < 3)
		{
			return;
		}

		List<object> msg = new List<object>();
		msg.Add(MsgDef.CLIENT2CELL_NAME_MSG);
		msg.Add(NameDef.SUBMSG_CHANGE_NAME);
		msg.Add(ifGiveName.text);
		KBEngine.Event.fireIn("sendCellMsg", msg);

		//IKernel.Instance().sendCellMsg(msg);

	}

	public void onDisconnected()
	{
		SceneManager.LoadScene("SceneLogin");
	}

	private void OnNameBtnClick()
	{
		Account account = (Account)KBEngineApp.app.player();
		if (account.name != "")
		{
			return;
		}
		transform.Find("pl_give_name").GetComponent<Image>().gameObject.SetActive(true);
		transform.Find("btn_name").GetComponent<Button>().enabled = false;
	}

	public void onNameChanged(string oldName)
	{
		Button btnName = transform.Find("btn_name").GetComponent<Button>();
		Text text = btnName.transform.Find("Text").GetComponent<Text>();
		Account acc = KBEngineApp.app.player() as Account;
		text.text = acc.name;
		transform.Find("pl_give_name").GetComponent<Image>().gameObject.SetActive(false);
	}

	public void onContainerPropChanged(int entityID, string propName, object oldValsL2, Int32 changeType)
	{
		if (propName != "capitals")
		{
			return;
		}

		Account account = (Account)KBEngineApp.app.player();
		var capitalsContainer = account.GetContainerProp(propName) as Dictionary<object, Dictionary<object, object>>;
		if (capitalsContainer == null)
		{
			return;
		}

		foreach (var capitalTypeAndInfoPair in capitalsContainer)
		{
			string name = Convert.ToString(capitalTypeAndInfoPair.Value["name"]);
			transform.Find("txt_" + name).GetComponent<Text>().text = Convert.ToString(capitalTypeAndInfoPair.Value["num"]);
		}

	}

	public void onHeadIconIDChanged(Int32 oldHeadID)
	{
		Account acc = KBEngineApp.app.player() as Account;
		Sprite spHeadIcon = Resources.Load(String.Format("head/head{0:D0}", acc.headIconID), typeof(Sprite)) as Sprite;
		transform.Find("img_head").GetComponent<Image>().sprite = spHeadIcon;
	}

	public void OnNameNetMsg(List<object> listMsg)
	{
		Int32 mainMsgID = Convert.ToInt32(listMsg[0]);
		if (mainMsgID != MsgDef.CELL2CLIENT_HALL_MSG)
		{
			return;
		}

		Int32 subMsg = Convert.ToInt32(listMsg[1]);
		switch (subMsg)
		{
			case NameDef.SUBMSG_CHANGE_NAME:
				Int32 result = Convert.ToInt32(listMsg[2]);
				break;
		}
	}

	public void OnMailNetMsg(List<object> listMsg)
	{
		Int32 mainMsgID = Convert.ToInt32(listMsg[0]);
		if (mainMsgID != MsgDef.CELL2CLIENT_MAIL_MSG)
		{
			return;
		}

		Int32 subMsg = Convert.ToInt32(listMsg[1]);
		switch (subMsg)
		{
			case MailDef.SUB_MSG_GET_MAIL_DATA:
				onNetMailMsg(listMsg);
				break;
		}
	}
}
